package com.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.project.bean.BuyBean;
import com.project.bean.BuyCartBean;
import com.project.bean.BuyDetailBean;
import com.project.mapper.IBuyCartMapper;
import com.project.mapper.IBuyDetailMapper;
import com.project.mapper.IBuyMapper;
import com.project.mapper.IProductMapper;
import com.project.service.IBuyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.util.List;

@Service
@Transactional
public class BuyServiceImpl implements IBuyService {
    @Autowired
    private IBuyMapper buyMapper;
    @Autowired
    private IBuyCartMapper buyCartMapper;
    @Autowired
    private IBuyDetailMapper buyDetailMapper;
    @Autowired
    private IProductMapper productMapper;

    @Override
    public void add(BuyBean buy, Integer userId) {
        //添加采购信息
        buyMapper.insert(buy);
        // 根据用户id查询购物车集合
        List<BuyCartBean> buyCartList = buyCartMapper.findByUserId(userId);
        // 批量添加采购明细，同时更新库存中的商品数量和最新采购价
        buyDetailMapper.addByBuyCartList(buy.getId(), buyCartList);

        productMapper.updateByBuyCartList(buyCartList);

        // 清空购物车
        QueryWrapper<BuyCartBean> qw = new QueryWrapper<>();
        qw.eq("fk_userId", userId);
        buyCartMapper.delete(qw);

    }

    @Override
    public IPage<BuyBean> cutByItem(Integer pageNO, String supplier, LocalDate startDate, LocalDate endDate) {
        QueryWrapper<BuyBean> qw = new QueryWrapper<>();
        if (supplier != null && !"".equals(supplier)) {
            qw.like("b_supplier",supplier);
        }
        if (startDate!=null){
            qw.ge("b_date",startDate);
        }
        if (endDate!=null){
            qw.le("b_date",endDate);
        }

        return buyMapper.selectPage(new Page<>(pageNO,5),qw);
    }

    @Override
    public BuyBean findById(Integer id) {
        BuyBean buy = buyMapper.selectById(id);
        List<BuyDetailBean> buyDetailList = buyDetailMapper.findByBuy(id);
        buy.setBuyDetailList(buyDetailList);
        return buy;
    }
}
